#!/bin/sh

# 应用名称
appName=CloudPush
homePath=/Users/vmu
appPath=/Applications
cpServer="http://192.154.223.27/"

# 当前路径
currentPath=$(cd `dirname $0`; pwd)
parentPath=`echo $(dirname "${currentPath}")`
cachePath=${currentPath}/cache

currentTime=`date +%s`
# 缓存更新App标识的文件
updateAppFile=${cachePath}/.updateApp
# 缓存重启App标识的文件
reRunAppFile=${cachePath}/.reRunApp
# 缓存业务动作以及超时时间的文件
actionExpireFile=${cachePath}/.actionExpire
currentAction=""	# 监控文件内容
subAction=""		# 动作名称
expireTime=""		# 过期时间
[[ -f "${actionExpireFile}" ]] && { currentAction=`cat ${actionExpireFile}`;}
# 解析动作名称和过期时间
[[ -n "${currentAction}" ]] && { 
	subAction=${currentAction%:*};
	expireTime=${currentAction#*:};
}

# 要升级的新版本号，为空则不升级
newVersion=""
[[ -f "${updateAppFile}" ]] && { newVersion=`cat ${updateAppFile}`; }

# 重启应用时间，为空则不重启
reRunAppTime=""
[[ -f "${reRunAppFile}" ]] && { reRunAppTime=`cat ${reRunAppFile}`; }




###########################
# 监控日志
###########################
monitorLog(){
	local dtime=`date +'%Y-%m-%d %H:%M:%S'`
	local datetime=`date +%Y%m%d`
	local logFile="${homePath}/.${appName}/logs/monitor_${datetime}.log"
	local content="[${dtime}]${1}"
	echo ${content} >> ${logFile}
	local logServer="http://log.cn-etc.com/cp/add"
	local app_id=`cat ${homePath}/CPFAppId.txt`
	local equ_id=`cat ${homePath}/.vmid.txt`
	# 传到云端
	curl -s  --data-urlencode app_id="${app_id}" --data-urlencode vmu_id="${equ_id}" --data-urlencode type=monitor --data-urlencode key=wdamao123 --data-urlencode content="${1}" --data-urlencode log_time="${dtime}" ${logServer}
}


###########################
# 移动鼠标
###########################
moveMouse(){
	local posx=$(($RANDOM%500+1))
	local posy=$(($RANDOM%500+1))
	/usr/bin/python -c "import Quartz.CoreGraphics  as qcg
def mouseMove(posx, posy):
	theEvent = qcg.CGEventCreateMouseEvent(None, qcg.kCGEventMouseMoved, (posx,posy), qcg.kCGMouseButtonLeft);
	qcg.CGEventPost(qcg.kCGHIDEventTap, theEvent);
mouseMove(${posx},${posy});
"
	#monitorLog "随机移动鼠标到(${posx},${posy})"
}



###########################
# 关闭应用/Messages/系统偏好设置
###########################
closeApp(){
	until [[ -z `ps -ef | grep "${appName}" | grep ".app" | grep -v grep | cut -c 8-13` ]]; do
		ps -ef | grep "${appName}" | grep ".app" | grep -v grep | cut -c 8-13| xargs kill -9
		sleep 1
	done
	sudo pkill "Messages"
	sudo pkill "System Preferences"
}

###########################
# 重启系统
###########################
restartOS(){
	# 强制退出云推/Messaegs/系统偏好设置
	sudo pkill "Messages"
	sudo pkill "System Preferences"
	# 重启后重新运行应用
	/bin/echo -n "${currentTime}" > "${reRunAppFile}"
	# 重启
	sudo shutdown -r now > /dev/null
}

###########################
# 重新运行应用
###########################
restartApp(){
	# 如果应用已启动则不理会
	if [[ `ps -ef | grep "${appName}" | grep ".app" | grep -v grep | wc -l` -gt 0 ]];then
		monitorLog "应用已启动，停止后重新开始"
		ps -ef | grep "${appName}" | grep ".app" | grep -v grep | cut -c 8-13| xargs kill -9
		sleep 2
	fi 
	# 强制退出云推/Messaegs/系统偏好设置
	sudo pkill "Messages"
	sudo pkill "System Preferences"
	# 启动应用
	. ${currentPath}/startup.sh
	
	sleep 3
	if [[ `ps -ef | grep "${appName}" | grep ".app" | grep -v grep | wc -l` -gt 0 ]];then
		rm -rf ${reRunAppFile}
		monitorLog "启动成功，清空文件"
	fi 
}




###########################
# 上报心跳【偶数分钟时上报】
###########################
heartbeat(){
	local currentMin=$((10#$(date +%M))) # 去掉前导0的分钟数
	local currentSec=$((10#$(date +%S))) # 去前导0的秒数
	if [[ $(( currentMin % 2 )) -eq 0 &&  "${currentSec}" -ge 0 && "${currentSec}" -le 12 ]];then
		local app_id=`cat ${homePath}/CPFAppId.txt`
		local equ_id=`cat ${homePath}/.vmid.txt`
		local resp=`curl -s -G --data-urlencode "app_id=${app_id}" --data-urlencode "equ_id=${equ_id}" ${cpServer}client/api/equipment/active`

		monitorLog "上报心跳"
		# 收到服务端指令，重置五码
		if [[ "${resp}" = "@reset_sn" ]];then
			cd ${cachePath}/
			ls | grep -v uuid | xargs rm -f
			monitorLog "心跳返回服务端重置五码指令"
			# 重启系统
			restartOS
		fi

		# 收到服务端指令，重置appleid
		if [[ "${resp}" = "@reset_appleid" ]];then
			cd ${cachePath}/
			ls | grep -v uuid | grep -v "applesn.txt" | xargs rm -f
			# 重置流程为登录iCloud
			echo "iCloudLogin:0" > action.txt
			monitorLog "心跳返回服务端重置ID指令"
			# 重启系统
			restartOS
		fi

		# 服务端自定义命令
		if [[ "${resp}" =~ "@cmd:" ]];then
			local cmd=${resp#*@cmd:}
			monitorLog "执行自定义命令${cmd}"
			`eval "${cmd}"`
		fi
	fi
}

# 更新应用
upadateApp() {
	
	monitorLog "开始升级版本，新版本：${newVersion}"
	cd ${appPath}
	# 3.1 先删除旧版本
	ls | grep "${appName}" | xargs rm -rf 

	# 3.2 下载新版
	local tmpAppName=CloudPush.tmp.zip
	local tmpFullPath=${appPath}${tmpAppName}
	
	curl -s --output "${tmpAppName}" ${cpServer}app/download
	until [[ -f "${tmpAppName}" ]];do
		sleep 1
	done
	
	/usr/bin/unzip -o  "${tmpAppName}" > /dev/null
	# 应用统一命名为CloudPushV+版本号
	if [[ ! -d "CloudPushV${newVersion}.app" ]];then
		mv CloudPush*.app "CloudPushV${newVersion}.app" > /dev/null
	fi

	# 删除临时文件
	rm -rf __MACOSX "${tmpAppName}"

	# 到这里应用其实已经升级了，因此可以把标志干掉
	rm -rf ${updateAppFile}

	# 这里设置App的启动时间3分钟后，避免App启动影响升级过程
	echo $(( currentTime + 180 )) > ${reRunAppFile}

	# 剩下的设置交给它了
	open /Applications/CPushReset.app
}



# 1、随机移动一下鼠标避免屏保
moveMouse

# 2、上报心跳
heartbeat



# 3 有版本更新
if [[ -n "${newVersion}" ]];then
	upadateApp
	exit 0
fi


# 4 重启应用,在升级时不能重启
if [[ -n "${reRunAppTime}" && -z "${newVersion}" ]]; then
	delayTime=$(( reRunAppTime - currentTime ))
	# 延迟时间
	if [[ "${delayTime}" -gt 10 ]];then
		exit 0
	fi
	sleep "${delayTime}"
	monitorLog "${subAction}应用重启"
	restartApp
	exit 0
fi


#  系统启动时间
#runTime=`uptime`
#startApp=0
#isLessFiveMin=0
#isMoreHour=1
#[[ "${runTime}" =~ "sec" ]] && { startApp=1; isLessFiveMin=1;isMoreHour=0;}
# 包含min即启动时间在1小时内，超过1小时显示格式为HH:MM
#if [[ "${runTime}" =~ "min" ]];then
#	runTimeRight=${runTime#*up}
#	runMins=${runTimeRight%min*}
#	isMoreHour=0
#	[[ "${runMins}" -lt 2 ]] && { startApp=1;}
#	[[ "${runMins}" -lt 5 ]] && { isLessFiveMin=1;}
#fi

# 5 应用没有启动，且也没有重启标志，主动拉起来
if [[ `ps -ef | grep "${appName}" | grep ".app" | grep -v grep | wc -l` -eq 0 &&  -z "${reRunAppTime}"  && -z "${newVersion}" ]];then
	# 对于拉起应用的情况，给30秒缓冲时间，方便人工介入
	sleep 30
	monitorLog "主动拉起应用"
	restartApp
	exit 0
fi




# 6 其它动在5分钟内不处理
#if [[ "${isLessFiveMin}" -eq 1 ]];then
#	monitorLog "启动时间小于5分钟"
#	exit 0
#fi


# 未超时则退出
[[ -z "${expireTime}" ]] && { exit 0;}

# 7 动作超时
if [[ "${currentTime}" -gt "${expireTime}"  && -z "${newVersion}" ]];then
	monitorLog "${subAction}超时重启"
	# 删除动作监控文件
	rm -rf ${actionExpireFile}
	restartOS
	exit 0
fi


